#!/bin/bash

# 启动应用程序
function start() {
    echo "启动应用程序..."
    if ! docker compose up -d; then
        echo "启动失败！"
        exit 1
    fi
}

# 编译、打包项目并启动应用程序
function build_and_start() {
    echo "编译和打包项目..."
    if ! mvn clean package -DskipTests; then
        echo "编译和打包失败！"
        exit 1
    fi

    services=$1
    if [ -z "$services" ]; then
        echo "构建所有 Docker 镜像..."
        if ! docker compose build; then
            echo "构建失败！"
            exit 1
        fi
    else
        IFS=',' read -ra ADDR <<< "$services"
        for service in "${ADDR[@]}"; do
            echo "构建 $service 服务的 Docker 镜像..."
            if ! docker compose build $service; then
                echo "$service 构建失败！"
                exit 1
            fi
        done
    fi

    start
}

# 停止应用程序
function stop() {
    echo "停止应用程序..."
    if ! docker compose down; then
        echo "停止失败！"
        exit 1
    fi
}

# 显示帮助信息
function show_help() {
    echo "使用说明:"
    echo "./start.sh start [-b service1,service2] | stop"
    echo "选项:"
    echo "  start        直接启动应用程序"
    echo "  start -b     编译、打包，并构建所有或指定服务，然后启动"
    echo "  stop         停止应用程序"
    echo "示例:"
    echo "  ./start.sh start                                直接启动应用程序"
    echo "  ./start.sh start -b                             编译、打包，并构建所有服务"
    echo "  ./start.sh start -b course-service,iam-service  编译、打包，并仅构建 course-service 和 iam-service 服务"
    echo "  ./start.sh stop                                 停止应用程序"
}

# 根据输入参数执行对应操作
case "$1" in
    start)
        if [ "$2" == "-b" ]; then
            build_and_start "$3"
        else
            start
        fi
        ;;
    stop)
        stop
        ;;
    *)
        show_help
        ;;
esac
